﻿using Report.WebApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToolManager.IService;
using Microsoft.Azure.Cosmos.Tables;
using Microsoft.Azure.Cosmos.Table;
using ToolManager.Entities;
using Report.WebApi.Models;
using Report.WebApi.Models.ResponseModel;
using System.Text;
using DataWasher.WebApi.Repositories;

namespace Report.WebApi.Services
{
    public class QueryWXSQSService : QueryService, IQueryWXSQSService
    {
        private readonly IStorageService _storageService;
        private readonly ISysDomainRepository _repository;
        public QueryWXSQSService(IStorageService storageService, ISysDomainRepository repository) : base(repository)
        {
            _storageService = storageService;
            _repository = repository;
        }

        public async Task<SQXResponse> GetHomePageData(QueryRequestModel request)
        {
            var response = new SQXResponse();
            var thisData = new List<BusinessDataEntity>();
            var YoYData = new List<BusinessDataEntity>();
            var DPData = new List<BusinessDataEntity>();

            ItemData itemData = null;
            var monthDatas = new List<ItemData>();

            //组装查询条件
            var thisYear = await GetMonthsThisYear(request);
            var filter = await ParamBuilder(request, thisYear);
            var query = new TableQuery<BusinessDataEntity>().Where(filter);
            var queryData = await _storageService.GetBusData("Businessdata", query);

            if (_connectionStrings.isDebug == 0)
            {
                var domainIds = await GetDomainIds(request);
                queryData = queryData.Where(x => domainIds.Contains(x.DomainId)).ToList();
            }

            //计算
            if (request.QueryByYear || request.QueryHomePage)
            {
                thisData = queryData.Where(x => x.AddDateYM >= thisYear.QueryBegin && x.AddDateYM <= thisYear.QueryEnd).ToList();
                YoYData = queryData.Where(x => x.AddDateYM >= thisYear.QueryBeginYoY && x.AddDateYM <= thisYear.QueryEndYoY).ToList();
            }
            else if (request.QueryByMonth || request.QueryByCustom || request.QueryByQuarter)
            {
                thisData = queryData.Where(x => x.AddDate >= thisYear.QueryBegin && x.AddDate <= thisYear.QueryEnd).ToList();
                YoYData = queryData.Where(x => x.AddDate >= thisYear.QueryBeginYoY && x.AddDate <= thisYear.QueryEndYoY).ToList();
            }

            response.Total = thisData.Count();
            response.YoY = YoYData.Count == 0 ? 0 : Math.Round((decimal)(thisData.Count - YoYData.Count) / YoYData.Count, 2);
            response.DP = 0;
            //如果是首页，直接返回数据
            if (request.QueryHomePage)
                return response;

            //遍历月，把当前和上一年的每个月的数据计算出来
            int temp = 0;
            thisYear.Items.ForEach(m =>
            {
                itemData = new ItemData();
                itemData.Index = m;
                itemData.ThisYear = request.QueryYear;
                itemData.PreYear = request.QueryYear - 1;
                if (request.QueryByYear)
                {
                    itemData.ThisYearCount = thisData.Where(x => x.AddDateMonth == m).Count();
                    itemData.PreYearCount = YoYData.Where(x => x.AddDateMonth == m).Count();
                }
                else if (request.QueryByMonth)
                {
                    itemData.ThisYearCount = thisData.Where(x => x.AddDateDay == m).Count();
                    itemData.PreYearCount = YoYData.Where(x => x.AddDateDay == m).Count();
                }
                else if (request.QueryByCustom)
                {
                    var Month = int.Parse(m.ToString().Split("709112")[0]);
                    var day = int.Parse(m.ToString().Split("709112")[1]);
                    itemData.ThisYearCount = thisData.Where(x => x.AddDateDay == day && x.AddDateMonth == Month).Count();
                    itemData.PreYearCount = YoYData.Where(x => x.AddDateDay == day && x.AddDateMonth == Month).Count();
                    itemData.Index = day;
                    itemData.Month = Month;
                }
                else if (request.QueryByQuarter)
                {
                    var quarter = thisYear.Quarters.Where(x => x.Month == m).FirstOrDefault();
                    itemData.ThisYearCount = thisData.Where(x => x.AddDate >= quarter.StartTime && x.AddDateMonth <= quarter.EndTime).Count();
                    itemData.PreYearCount = YoYData.Where(x => x.AddDate >= quarter.YOYStartTime && x.AddDate <= quarter.YOYEndTime).Count();
                }


                itemData.YoY = itemData.PreYearCount == 0 ? 0 : Math.Round((decimal)(itemData.ThisYearCount - itemData.PreYearCount) / itemData.PreYearCount, 2);

                if (m >= 2)
                {
                    itemData.DP = temp == 0 ? 0 : Math.Round((decimal)(itemData.ThisYearCount - temp) / temp, 2);
                }
                temp = itemData.ThisYearCount;
                monthDatas.Add(itemData);
            });



            response.ItemDatas = monthDatas;

            return response;



        }

        public async override Task<string> ParamBuilder(QueryRequestModel request, YearMonthModel filterModel)
        {
            var partitionKey = DateTime.Now.ToString("yyyyMMdd");
            var filterSB = new StringBuilder();
            filterSB.Append($"(PartitionKey eq '{partitionKey}')");
            filterSB.Append(" and ");

            filterSB.Append($"((AddDateYear eq {filterModel.Year})");
            filterSB.Append(" or ");
            filterSB.Append($"(AddDateYear eq {filterModel.Year - 1}))");

            #region 条件组合
            filterSB.Append(" and ");
            filterSB.Append($"(Language eq {request.Language})");

            if (!string.IsNullOrEmpty(request.QueryStore))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(TagName eq '{request.QueryStore}')");
            }

            if (!string.IsNullOrEmpty(request.QueryStatus))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(MntStatus eq '{request.QueryStatus}')");
            }

            if (!string.IsNullOrEmpty(request.QueryPriority))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(Priority eq '{request.QueryPriority}')");
            }
            if (!string.IsNullOrEmpty(request.QueryMntanCategory))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(MntCategory2 eq '{request.QueryMntanCategory}')");
            }
            #endregion
            return filterSB.ToString();
        }

    }
}
